package com.adams.app.ui.fragment;

import java.util.ArrayList;

import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.adams.app.R;
import com.adams.app.dao.AttractionDataHelper;
import com.adams.app.data.GsonRequest;
import com.adams.app.model.Attractions;
import com.adams.app.ui.CompassActivity;
import com.adams.app.ui.MainActivity;
import com.adams.app.ui.StepStartActivity;
import com.adams.app.ui.TravelDetailActivity;
import com.adams.app.ui.adapter.AttractionsAdapter;
import com.adams.app.ui.adapter.CardsAnimationAdapter;
import com.adams.app.ui.view.LoadingFooter;
import com.adams.app.utils.CommonUtils;
import com.adams.app.vendor.HappyGyApi;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.haarman.listviewanimations.swinginadapters.AnimationAdapter;

/**
 * Created by Adams on 13-12-27.
 */
public class AttractionsFragment extends BaseFragment implements
		LoaderManager.LoaderCallbacks<Cursor>,
		PullToRefreshAttacher.OnRefreshListener {

	private ListView mListView;
	private AttractionDataHelper mDataHelper;
	private AttractionsAdapter mAdapter;
	private PullToRefreshAttacher mPullToRefreshAttacher;
	private LoadingFooter mLoadingFooter;
	private int mPage = 1;

	public AttractionsFragment() {

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View contentView = inflater
				.inflate(R.layout.fragment_attractions, null);
		mListView = (ListView) contentView.findViewById(R.id.listView);

		// Attractions数据库
		mDataHelper = new AttractionDataHelper(getActivity());
		mAdapter = new AttractionsAdapter(getActivity(), mListView);

		View header = new View(getActivity());

		// 下拉刷新
		mPullToRefreshAttacher = ((MainActivity) getActivity())
				.getPullToRefreshAttacher();
		mPullToRefreshAttacher.setRefreshableView(mListView, this);

		// 脚部加载
		mLoadingFooter = new LoadingFooter(getActivity());

		// listView添加控件
		mListView.addHeaderView(header);
		mListView.addFooterView(mLoadingFooter.getView());

		// 动画适配器
		AnimationAdapter animationAdapter = new CardsAnimationAdapter(mAdapter);
		animationAdapter.setListView(mListView);
		mListView.setAdapter(animationAdapter);

		setHasOptionsMenu(true);

		// 准备装载器
		getLoaderManager().initLoader(0, null, this);

		// ListView滑动监听
		mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (mLoadingFooter.getState() == LoadingFooter.State.Loading
						|| mLoadingFooter.getState() == LoadingFooter.State.TheEnd) {
					return;
				}
				if (firstVisibleItem + visibleItemCount >= totalItemCount
						&& totalItemCount != 0
						&& totalItemCount != mListView.getHeaderViewsCount()
								+ mListView.getFooterViewsCount()
						&& mAdapter.getCount() > 0) {
					loadNextPage();
				}
			}
		});
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				Attractions attractions = mAdapter.getItem(position - mListView.getHeaderViewsCount());
				Intent intent = new Intent(getActivity(),
						TravelDetailActivity.class);
				intent.putExtra("attractions", attractions);
				getActivity().startActivity(intent);
			}
		});

		return contentView;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		menu.add("健康旅行").setTitle("健康旅行")
				.setIntent(new Intent(getActivity(), StepStartActivity.class))
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		menu.add("指南针").setTitle("指南针")
				.setIntent(new Intent(getActivity(), CompassActivity.class))
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mPullToRefreshAttacher.getHeaderTransformer().onConfigurationChanged(
				getActivity());
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	private void loadNextPage() {
		mLoadingFooter.setState(LoadingFooter.State.Loading);
		loadData(mPage + 1);
	}

	private void loadFirstPage() {
		loadData(1);
	}

	// 加载数据
	private void loadData(final int page) {
		final boolean isRefreshFromTop = page == 1;
		if (!mPullToRefreshAttacher.isRefreshing() && isRefreshFromTop) {
			mPullToRefreshAttacher.setRefreshing(true);
		}
		executeRequest(new GsonRequest<Attractions.AttractionRequestData>(
				String.format(HappyGyApi.SHOTS_LIST, page),
				Attractions.AttractionRequestData.class, null,
				new Response.Listener<Attractions.AttractionRequestData>() {
					@Override
					public void onResponse(
							final Attractions.AttractionRequestData requestData) {
						CommonUtils
								.executeAsyncTask(new AsyncTask<Object, Object, Object>() {
									@Override
									protected Object doInBackground(
											Object... params) {
										if (requestData.getAttractions().size() > 0) {
											mPage = page;
											if (mPage == 1) {
												mDataHelper.deleteAll();
												System.out.println("del");
											}
											ArrayList<Attractions> attractions = requestData
													.getAttractions();
											mDataHelper.bulkInsert(attractions);
										}
										System.out.println(mPage);
										return null;
									}

									@Override
									protected void onPostExecute(Object o) {
										super.onPostExecute(o);
										if (isRefreshFromTop) {
											mPullToRefreshAttacher
													.setRefreshComplete();
										} else {
											mLoadingFooter.setState(
													LoadingFooter.State.Idle,
													3000);
	
										}
									}
								});
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError volleyError) {
						Toast.makeText(getActivity(),
								R.string.refresh_list_failed,
								Toast.LENGTH_SHORT).show();
						if (isRefreshFromTop) {
							mPullToRefreshAttacher.setRefreshComplete();
						} else {
							mLoadingFooter.setState(LoadingFooter.State.Idle,
									3000);
						}
					}
				}));
	}

	// //////////////////////////
	//
	// LoaderCallbacks
	//
	// /////////////////////////
	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		return mDataHelper.getCursorLoader();
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		mAdapter.changeCursor(data);
		if (data != null && data.getCount() == 0) {
			loadFirstPage();
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mAdapter.changeCursor(null);
	}

	// //////////////////////////
	//
	// OnRefreshListener
	//
	// /////////////////////////
	@Override
	public void onRefreshStarted(View view) {
		loadFirstPage();
	}

}
